
import 'dart:convert';
import 'dart:io';

import 'package:afmjb1/mjb/log_utls.dart';
import 'package:appsflyer_sdk/appsflyer_sdk.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:webview_flutter/webview_flutter.dart';

// #docregion platform_imports
// Import for Android features.
//
// void main() {
//   runApp(const MyApp());
// }

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        // appBar: AppBar(
        //     title: const Text(
        //   "com.sample.advent",
        //   textDirection: TextDirection.ltr,
        // )),
        body: BWeb(),
      ),
    );
  }
}

class BWeb extends StatefulWidget {
  const BWeb({Key? key}) : super(key: key);

  @override
  _BWebState createState() => _BWebState();
}

class _BWebState extends State<BWeb> {
  WebViewController? _controller;
  late AppsflyerSdk _appsflyerSdk;

  void printLog(Object? msg) {
    print("lihui>>>$msg");
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //com.hdknf.jdnbdjnfnbc	MuHPbGB2m7tXBVbBBT9YNS
    final AppsFlyerOptions options = AppsFlyerOptions(
        afDevKey: "a6ugFwuge2fBcVeMfyjYWY",
        showDebug: true,
        timeToWaitForATTUserAuthorization: 15);
    _appsflyerSdk = AppsflyerSdk(options);
    _appsflyerSdk.onInstallConversionData((res) {
      printLog("onInstallConversionData res: " + res.toString());
    });

    _appsflyerSdk.initSdk(
      registerConversionDataCallback: true,
    );
  }

  @override
  Widget build(BuildContext context) {
    String url = "";
    if (Platform.isAndroid) {
      url = "https://www.abcd33.bet?pid=1121";
    } else if (Platform.isIOS) {
      url = "";
    }

    return Scaffold(
      body: Container(
        color: Colors.black,
        child: Padding(
          padding: const EdgeInsets.only(top: 40),
          child:WebView(
            initialUrl: url,
            javascriptMode: JavascriptMode.unrestricted,
            javascriptChannels: {
              // JavascriptChannel(
              //     name: "toast",
              //     onMessageReceived: (message) {
              //       Fluttertoast.showToast(msg: message.message.toString());
              //     }),
              // JavascriptChannel(
              //     name: "jscomm",
              //     onMessageReceived: (message) {
              //       Fluttertoast.showToast(msg: message.message.toString());
              //     }),
              JavascriptChannel(
                  name: "apkClient",
                  onMessageReceived: (message) {
                    printLog("msg===" + message.toString());
                    Fluttertoast.showToast(msg: message.message);
                    /**
                     * 登录window.apkClient.appsFlyerEvent(JSON.stringify({"event_type": "af_login", "uid": res.data.uid}))
                     */
                    Map<String, dynamic> map = jsonDecode(message.message);
                    printLog("jsonDecode map===" + message.toString());

                    logEvent(map["event_type"], map).then(
                            (value) => {
                          printLog("logEvent map=" + map.toString()+",value="+value.toString())

                        });
                  }),
            },
            onWebViewCreated: (controller) {
              _controller = controller;
            },
          )
        ),
      ),
    );
  }

  Future<bool?> logEvent(String eventName, Map eventValues) {
    printLog(
        "eventName=" + eventName + ",eventValues=" + eventValues.toString());
    return _appsflyerSdk.logEvent(eventName, eventValues);
  }
}

class Web extends StatefulWidget {
  String url = "";

  Web({Key? key, url = ""}) : super(key: key);

  @override
  _WebState createState() => _WebState();
}

class _WebState extends State<Web> {
  WebViewController? _controller;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ElevatedButton(
          onPressed: () {
            if (_controller != null) {
              _controller!
                  .runJavascriptReturningResult(
                      "flutterCallJsMethod('Flutter调用了JS')")
                  .then((value) {
                Fluttertoast.showToast(msg: value.toString());
              });
            }
          },
          child: Text("点击Flutter调用JS有返回值"),
        ),
        ElevatedButton(
          onPressed: () {
            if (_controller != null) {
              _controller!
                  .runJavascript("flutterCallJsMethodNoResult('Flutter调用了JS')");
            }
          },
          child: Text("点击Flutter调用JS无返回值"),
        ),
        Padding(padding: EdgeInsets.only(top: 10)),
        Flexible(
            child: WebView(
          initialUrl: widget.url,
          javascriptMode: JavascriptMode.unrestricted,
          javascriptChannels: {
            // JavascriptChannel(
            //     name: "toast",
            //     onMessageReceived: (message) {
            //       printLog("1 msg==="+message.toString());
            //       Fluttertoast.showToast(msg: message.message.toString());
            //     }),
            JavascriptChannel(
                name: "apkClient",
                onMessageReceived: (message) {
                  printLog("2 msg==="+message.toString());
                  Fluttertoast.showToast(msg: message.message.toString());
                }),
          },
          onWebViewCreated: (controller) {
            _controller = controller;
          },
        ))
      ],
    );
  }
}
